package com.iflytek.edu.pdc.uc.elasticsearch.support.Builder;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.Iterator;
import java.util.Map;

/**
 * @Description:
 * @author: liux
 * @date: 2019/3/8 11:46 PM
 */
public class QueryConditionsBuilder {


    public BoolQueryBuilder queryBuilder;
    public String operator;
    /**
     * 构建一个Wildcard的查询条件
     *
     * @param searchMap
     * @return
     */
    public QueryConditionsBuilder buildWildcardSearch(Map<String, Object> searchMap) {
        if (searchMap == null) {
            return null;
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Iterator iterator = searchMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            //字段
            String filed = entry.getKey().toString();
            //值
            Object value = entry.getValue();
            boolQueryBuilder.must(QueryBuilders.wildcardQuery(filed, "*" + value.toString() + "*"));
        }
        queryBuilder = boolQueryBuilder;
        return this;
    }

    /**
     * 构建一个Term的查询条件
     *
     * @param searchMap
     * @return
     */
    public QueryConditionsBuilder buildTermSearch(Map<String, Object> searchMap) {
        if (searchMap == null) {
            return null;
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Iterator iterator = searchMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            //字段
            String filed = entry.getKey().toString();
            //值
            Object value = entry.getValue();
            boolQueryBuilder.must(QueryBuilders.termQuery(filed, value));
        }
        queryBuilder = boolQueryBuilder;
        return this;
    }

    /**
     * 暂时未使用,后续需要优化
     * @param andOr
     * @return
     */
    @Deprecated
    public QueryConditionsBuilder buildOperator(String andOr){
        operator=andOr;
        return this;
    }


    public QueryCondition build() {
        return new QueryCondition(this);
    }


}
